// 引入axios
import axios from 'axios';
import {Message} from 'element-ui';
import deviceUtil from './deviceUtil';
import Vue from 'vue';

const api = '/api';

// 创建axios实例
const httpService = axios.create({
    // url前缀-'http:xxx.xxx'
    baseURL: process.env.BASE_API, // 需自定义
    // 请求超时时间
    timeout: 5000 // 需自定义
});

// request拦截器
httpService.interceptors.request.use(

    config => {
        // 根据条件加入token-安全携带
        var needToken = true;
        if (needToken) { // 需自定义
            // 让每个请求携带token
            let token = localStorage.getItem("token");
            console.log("请求携带token：" + token)
            if(token != null && token != undefined && token != 'undefined'){
              config.headers['Authorization'] = token;
            }
        }
        return config;
    },
    error => {
        // 请求错误处理
        Promise.reject(error);
    }
)

// respone拦截器
httpService.interceptors.response.use(
    response => {
        // 统一处理状态
        const res = response.data;
        console.log("axiosUtil返回值............")
        console.log(res);
        if (res.status != 200 && res.status != 400 && res.status != 401) { // 需自定义
            Message.error(res.message);
        } else if(res.status == 401){ //如果是未授权，需要登录后进行操作，弹出登录框
          if(deviceUtil.isPhone()){
            // console.log(Vue.prototype)
            // Vue.prototype.$showMLoginForm();
            // Vue.prototype.$toast("请登录后操作");
            // Vue.prototype.$showMLoginForm();
          } else {
            // Vue.prototype.$showPcLoginForm();
            // Message.warn("请登录后操作");
            // alert("请登陆后操作");
            // 清除认证信息
            localStorage.removeItem("token");
            localStorage.removeItem("userInfo");
            Message.error("认证失败，请登录后操作");
          }
        } else {
            var token = response.headers['authorization'];
           if(token != null){
             // 设置认证信息
             localStorage.setItem("token", token);
             console.log("设置认证信息完成")
           }
            return response.data;
        }
    },
    // 处理处理
    error => {
         //alert(error);
         if (error && error.response) {
            switch (error.response.status) {
                case 400:
                    error.message = '错误请求';
                    break;
                case 401:
                    error.message = '未授权，请重新登录';
                    break;
                case 403:
                    error.message = '拒绝访问';
                    break;
                case 404:
                    error.message = '请求错误,未找到该资源';
                    break;
                case 405:
                    error.message = '请求方法未允许';
                    break;
                case 408:
                    error.message = '请求超时';
                    break;
                case 500:
                    error.message = '服务器端出错';
                    break;
                case 501:
                    error.message = '网络未实现';
                    break;
                case 502:
                    error.message = '网络错误';
                    break;
                case 503:
                    error.message = '服务不可用';
                    break;
                case 504:
                    error.message = '网络超时';
                    break;
                case 505:
                    error.message = 'http版本不支持该请求';
                    break;
                default:
                    error.message = `未知错误${error.response.status}`;
            }
        } else {
            error.message = "连接到服务器失败";
        }

        if(deviceUtil.isPhone()){
            Vue.prototype.$toast(error.message);
        }else {
            Message.error(error.message);
        }

        return Promise.reject(error);
    }
)

/*网络请求部分*/

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
export function get(url, params, headers) {
    return new Promise((resolve, reject) => {
        httpService({
            url:  url,
            method: 'get',
            params: params,
            headers: headers,
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export function post(url, params = {},headers) {
    return new Promise((resolve, reject) => {
        httpService({
            url:  url,
            method: 'post',
            data: params,
            headers: headers
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export function del(url, params, headers) {
    return new Promise((resolve, reject) => {
        httpService({
            url:  url,
            method: 'delete',
            params: params,
            headers: headers,
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

/*
 *  文件上传
 *  url:请求地址
 *  params:参数
 * */
export function fileUpload(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: api + url,
            method: 'post',
            data: params,
            headers: { 'Content-Type': 'multipart/form-data' }
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export function postWithResHead(url, params = {}, headers = {}){
  url = api + url;
  return axios.post(url, params);
}

export default {
    get,
    post,
    del,
    fileUpload,
    postWithResHead
}
